// pages/profile/profile.js
const storage = require('../../utils/storage.js');
const cloudService = require('../../utils/cloud/cloudService.js');

Page({
  data: {
    userInfo: {},
    stats: {
      totalGames: 0,
      winRate: 0,
      avgTime: '-',
      fastestTime: '-'
    },
    manualStats: {
      count: 0,
      avgTime: '-'
    },
    autoStats: {
      count: 0,
      avgTime: '-'
    },
    difficultyStats: {
      easy: 0,
      medium: 0,
      hard: 0
    },
    recentGames: []
  },

  onLoad() {
    this.loadUserInfo();
    this.loadStatistics();
  },

  onShow() {
    // 每次显示页面时刷新数据
    this.loadStatistics();
  },

  /**
   * 加载用户信息
   */
  loadUserInfo() {
    const userInfo = wx.getStorageSync('userInfo');
    if (userInfo) {
      this.setData({
        userInfo: userInfo
      });
    }
  },

  /**
   * 加载统计数据
   */
  loadStatistics() {
    const allGames = storage.getGameHistory();
    const stats = storage.getStatistics();

    // 基础统计
    const totalGames = allGames.length;
    const successGames = allGames.filter(g => g.success).length;
    const winRate = totalGames > 0 ? Math.round((successGames / totalGames) * 100) : 0;

    // 计算平均用时和最快记录
    const successfulGames = allGames.filter(g => g.success && g.duration);
    let avgTime = '-';
    let fastestTime = '-';
    
    if (successfulGames.length > 0) {
      const totalDuration = successfulGames.reduce((sum, g) => sum + g.duration, 0);
      avgTime = this.formatDuration(Math.floor(totalDuration / successfulGames.length));
      
      const minDuration = Math.min(...successfulGames.map(g => g.duration));
      fastestTime = this.formatDuration(minDuration);
    }

    // 手动/自动统计
    const manualGames = allGames.filter(g => g.solveType === 'manual');
    const autoGames = allGames.filter(g => g.solveType === 'auto');
    
    let manualAvgTime = '-';
    if (manualGames.length > 0) {
      const manualTotal = manualGames.reduce((sum, g) => sum + (g.duration || 0), 0);
      manualAvgTime = this.formatDuration(Math.floor(manualTotal / manualGames.length));
    }
    
    let autoAvgTime = '-';
    if (autoGames.length > 0) {
      const autoTotal = autoGames.reduce((sum, g) => sum + (g.duration || 0), 0);
      autoAvgTime = this.formatDuration(Math.floor(autoTotal / autoGames.length));
    }

    // 难度统计
    const difficultyStats = {
      easy: allGames.filter(g => g.difficulty === 'easy').length,
      medium: allGames.filter(g => g.difficulty === 'medium').length,
      hard: allGames.filter(g => g.difficulty === 'hard').length
    };

    // 最近5局游戏
    const recentGames = allGames.slice(0, 5).map(game => ({
      ...game,
      formattedTime: this.formatDateTime(game.timestamp),
      formattedDuration: this.formatDuration(game.duration)
    }));

    this.setData({
      stats: {
        totalGames,
        winRate,
        avgTime,
        fastestTime
      },
      manualStats: {
        count: manualGames.length,
        avgTime: manualAvgTime
      },
      autoStats: {
        count: autoGames.length,
        avgTime: autoAvgTime
      },
      difficultyStats,
      recentGames
    });
  },

  /**
   * 格式化时长
   */
  formatDuration(seconds) {
    if (!seconds) return '-';
    const minutes = Math.floor(seconds / 60);
    const secs = seconds % 60;
    if (minutes > 0) {
      return `${minutes}分${secs}秒`;
    }
    return `${secs}秒`;
  },

  /**
   * 格式化日期时间
   */
  formatDateTime(timestamp) {
    const date = new Date(timestamp);
    const now = new Date();
    const diff = now - date;
    
    // 今天
    if (diff < 24 * 60 * 60 * 1000 && date.getDate() === now.getDate()) {
      const hours = date.getHours().toString().padStart(2, '0');
      const minutes = date.getMinutes().toString().padStart(2, '0');
      return `今天 ${hours}:${minutes}`;
    }
    
    // 昨天
    if (diff < 48 * 60 * 60 * 1000) {
      const yesterday = new Date(now);
      yesterday.setDate(yesterday.getDate() - 1);
      if (date.getDate() === yesterday.getDate()) {
        const hours = date.getHours().toString().padStart(2, '0');
        const minutes = date.getMinutes().toString().padStart(2, '0');
        return `昨天 ${hours}:${minutes}`;
      }
    }
    
    // 其他日期
    const month = (date.getMonth() + 1).toString().padStart(2, '0');
    const day = date.getDate().toString().padStart(2, '0');
    return `${month}-${day}`;
  },

  /**
   * 查看手动完成历史
   */
  viewManualHistory() {
    wx.navigateTo({
      url: '/pages/history/history?filter=manual'
    });
  },

  /**
   * 查看自动求解历史
   */
  viewAutoHistory() {
    wx.navigateTo({
      url: '/pages/history/history?filter=auto'
    });
  },

  /**
   * 编辑用户信息
   */
  editUserInfo() {
    const that = this
    
    wx.showActionSheet({
      itemList: ['修改昵称', '更换头像'],
      success(res) {
        if (res.tapIndex === 0) {
          // 修改昵称
          that.editNickname()
        } else if (res.tapIndex === 1) {
          // 更换头像
          that.changeAvatar()
        }
      }
    })
  },

  /**
   * 修改昵称
   */
  editNickname() {
    const that = this
    const currentNickname = this.data.userInfo.nickName || ''
    
    wx.showModal({
      title: '修改昵称',
      editable: true,
      placeholderText: '请输入新昵称',
      content: currentNickname,
      success: async (res) => {
        if (res.confirm && res.content) {
          const newNickname = res.content.trim()
          
          if (newNickname.length === 0) {
            wx.showToast({
              title: '昵称不能为空',
              icon: 'none'
            })
            return
          }
          
          if (newNickname.length > 20) {
            wx.showToast({
              title: '昵称不能超过20字',
              icon: 'none'
            })
            return
          }
          
          wx.showLoading({ title: '保存中...' })
          
          // 更新到云端
          const result = await cloudService.updateUserInfo({
            nickName: newNickname
          })
          
          wx.hideLoading()
          
          if (result.success) {
            // 更新本地用户信息
            const userInfo = that.data.userInfo
            userInfo.nickName = newNickname
            wx.setStorageSync('userInfo', userInfo)
            
            that.setData({ userInfo })
            
            wx.showToast({
              title: '修改成功',
              icon: 'success'
            })
          } else {
            wx.showToast({
              title: '修改失败',
              icon: 'none'
            })
          }
        }
      }
    })
  },

  /**
   * 更换头像
   */
  async changeAvatar() {
    const that = this
    
    try {
      // 选择图片
      const chooseResult = await wx.chooseMedia({
        count: 1,
        mediaType: ['image'],
        sizeType: ['compressed'], // 压缩图
        sourceType: ['album', 'camera']
      })
      
      if (!chooseResult.tempFiles || chooseResult.tempFiles.length === 0) {
        return
      }
      
      const tempFile = chooseResult.tempFiles[0]
      const fileSize = tempFile.size
      
      // 限制图片大小为 2MB
      if (fileSize > 2 * 1024 * 1024) {
        wx.showToast({
          title: '图片不能超过2MB',
          icon: 'none',
          duration: 2000
        })
        return
      }
      
      wx.showLoading({ title: '上传中...' })
      
      // 获取 openId
      const openIdResult = await cloudService.getUserOpenId()
      
      if (!openIdResult.success) {
        wx.hideLoading()
        wx.showToast({
          title: '获取用户信息失败',
          icon: 'none'
        })
        return
      }
      
      const openId = openIdResult.openId
      
      // 上传到云存储
      const uploadResult = await cloudService.uploadAvatar(tempFile.tempFilePath, openId)
      
      if (!uploadResult.success) {
        wx.hideLoading()
        wx.showToast({
          title: '上传失败',
          icon: 'none'
        })
        return
      }
      
      const avatarUrl = uploadResult.fileID
      
      // 更新到云端数据库
      const updateResult = await cloudService.updateUserInfo({
        avatarUrl: avatarUrl
      })
      
      wx.hideLoading()
      
      if (updateResult.success) {
        // 更新本地用户信息
        const userInfo = that.data.userInfo
        userInfo.avatarUrl = avatarUrl
        wx.setStorageSync('userInfo', userInfo)
        
        that.setData({ userInfo })
        
        wx.showToast({
          title: '头像更新成功',
          icon: 'success'
        })
      } else {
        wx.showToast({
          title: '更新失败',
          icon: 'none'
        })
      }
    } catch (err) {
      wx.hideLoading()
      console.error('更换头像失败:', err)
      wx.showToast({
        title: '操作失败',
        icon: 'none'
      })
    }
  },

  /**
   * 返回游戏
   */
  goBack() {
    wx.navigateBack();
  }
});
